package com.zhuqi.handler;

import com.zhuqi.proto.LoginMessageProto;
import com.zhuqi.proto.build.LoginMessageProtoBuild;
import com.zhuqi.proto.cost.MessageProtocolBufEnum;
import com.zhuqi.service.ChatUserService;
import com.zhuqi.service.session.Session;
import com.zhuqi.session.messge.MessagePackage;
import io.netty.channel.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author ZhuQi
 * @ClassName LoggingRequestMessageHandel
 * @Date 2023/1/16 16:35
 * @Version 1.0
 * @Description 登陆处理器
 */
@Slf4j
@ChannelHandler.Sharable
@Component
public class LoggingRequestMessageHandel extends SimpleChannelInboundHandler<LoginMessageProto.LoginMessageRequest> {

	@Resource
	private ChatUserService chatUserService;

	@Resource
	private Session session;

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, LoginMessageProto.LoginMessageRequest msg) {
		String username = msg.getUsername().trim();
		String password = msg.getPassword().trim();
		log.debug("登陆的 用户名：{} 密码：{}", username, password);
		Channel channel = session.getChannel(username);
		LoginMessageProto.LoginMessageResponse loginResponseMessage;

		if (channel != null) {
			// 重复登陆返回成功
			loginResponseMessage = LoginMessageProtoBuild.createLoginResponseMessage(true, "重复登陆", username);
		} else {
			if (chatUserService.login(username, password)) {
				log.info("{},登陆成功", username);
				session.bind(ctx.channel(), username);
				loginResponseMessage = LoginMessageProtoBuild.createLoginResponseMessage(true, "登陆成功", username);
			} else {
				log.warn("用户名密码不正确！！！");
				loginResponseMessage = LoginMessageProtoBuild.createLoginResponseMessage(false, "账号密码有误",
						username);
			}
		}
		MessagePackage messagePackage = new MessagePackage();
		messagePackage.setBusinessCode(MessageProtocolBufEnum.LOGIN_RESPONSE_MESSAGE.getCode());
		messagePackage.setData(loginResponseMessage.toByteArray());
		ChannelFuture channelFuture = ctx.channel().writeAndFlush(messagePackage);
		// 结果确认
		ensure(username, channelFuture);
	}

	/**
	 * 确认发送结果
	 */
	private static void ensure(String username, ChannelFuture channelFuture) {
		channelFuture.addListener((ChannelFutureListener) future -> log.info("登陆消息发送成功:{}", username));
	}
}
